﻿using UnityEngine;

namespace Global.Tool
{
    /// <summary>
    /// Unity全局单例模板
    /// </summary>
    /// <typeparam name="T">组件类型</typeparam>
    public class UnityGolbalSingleton <T>: MonoBehaviour 
        where T : Component
    {
        private static T _instance;
        public static T Instance
        {
            get
            {
                if (_instance != null) return _instance;
                _instance = FindObjectOfType<T>();
                if (_instance != null) return _instance;
                var obj = new GameObject {hideFlags = HideFlags.HideAndDontSave};
                _instance = obj.AddComponent<T>();
                return _instance;
            }
        }

        public virtual void Awake()
        {
        
            if (_instance == null)
            {
                _instance = this as T;
            }
            else
            {
                Destroy(gameObject);
                return;
            }
            DontDestroyOnLoad(this.gameObject);
        }
    }
}
